import React from 'react';
import { findDOMNode } from 'react-dom';
import cx from 'classnames';
import style from './style.objective-relative-tree-view';
import util from '../../util';
import { Progress, Avatar, Link, Button, Loading } from 'sq-ui';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import * as okrAction from '../../actions/okr.action'
import { setStepGuide, updateGuide } from '../../actions/app.action'
import { Motion, spring } from 'react-motion';
import sliceArray from 'sliceArray';
import moment from 'moment';
import { withRouter } from 'react-router';
import { NextGuide } from '../guide/Guide';

function _Card(props) {
  if (props.isFetching) {
    return (
      <div className={cx(style.card, props.className)}>
        <div>
          <Loading small style={{
            position: 'absolute',
            left: '50%',
            top: '50%',
            marginLeft: '-9px',
            marginTop: '-9px',
          }}/>
        </div>
      </div>
    )
  }
  const {
    content,
    className,
    hasParent,
    hasSubordinate,
    avatarUrl,
    isSelf,
    isParent,
    isAutoCalc,
    startingAmount,
    currentAmount,
    goalAmount,
    unit,
    progressMetricType,
    objectivePeriodOwnerName,
    objectivePeriodOwnerJobTitleName,
    lastModifiedTime,
    router,
    query,
    directorList,
    type,
    isBird,
    progress,
  } = props;

  const directors = (directorList || []).slice(0, 3);

  const href = props.to ? {
    onClick: e => {
      router.push(props.to.slice(1));
    }
  }: {};

  return React.createElement('div', {
    ...href,
    className: cx(style.card, {
      [className]: className,
      [style.clickable]: /*hasParent && */hasSubordinate && !isSelf,
      [style.disable]: !(/*hasParent && */hasSubordinate && !isSelf) && !isSelf && !isBird,

    }),
  }, 
    <div>
      <div className={style['card-top']}>
        {
          !isBird ?
            <div className={cx(style['indicator'], style[`indicator-${type}`])}></div>
          : null
        }
        <div style={{ height: isParent ? '42px' : '66px' }}>
          <Link
            target="_blank"
            onClick={e => util.stopPropagation(e)}
            to={`/okr/objectives/${props.objectiveId}?${util.body(query)}`} className={style.content}><span>{util.strSlice(content || '', 0, 28)}{util.strLen(content || '') > 28 ? '...' : ''}</span></Link>
          {
            (!isParent && lastModifiedTime) ?
            <p className={style['last-update']}>{moment(+lastModifiedTime).fromNow()}</p>
            : null
          }
        </div>
        <div className={style.user}>
          <Avatar
            src={avatarUrl}
            width={32}
            className={style.avatar}
          />
          <div>
            <p className={style.fullname}>{objectivePeriodOwnerName}</p>
            {
              type == 3 ?
              <p className={style.title}>{objectivePeriodOwnerJobTitleName}</p>
              : (
                <p className={style.title}>项目负责：{util.isNull(directorList) ? '无' : directors.map((user, i) =>(
                  <span key={i}>
                    <Link
                      target="_blank"
                      label={user.coreUserProfileVO.fullName}
                      to={`/okr/objective-targetAll?userId=${user.coreUserProfileVO.userId}`}
                    />
                    {
                      i < directors.length - 1 ? (
                        <span>、</span>
                      ) : null
                    }
                  </span>
                  ))}{ (directorList || []).length > 3 ? '等' : '' }</p>
              )
            }
          </div>
        </div>
      </div>
      {
        !isParent ? <hr/> : null
      }
      {
        !isParent ? (
          <p className={style.amount}>
            {
              isAutoCalc ?
              <span>进度：{(progress || 0)* 100}%</span>
              : (
                currentAmount == null ? null : (
                  <span>进度：{progressMetricType == 1? `${currentAmount}%`: `${currentAmount}/${goalAmount}${unit}（初始值：${startingAmount}）`}</span>
                )
              )
            }
          </p>
        ) : null
      }
      <Progress
        className={style.progress}
        line
        value={progress ? progress* 100 : 0}
        width={isParent ? 336 : 238}
        height={5}
      />
    </div>
  );
}

export
const Card = withRouter(_Card);

export default
@connect(({ okr, app }) => ({ okr, app }), dispatch => ({actions: bindActionCreators({...okrAction, updateGuide, setStepGuide }, dispatch)}))
class ObjectiveRelativeTreeView extends React.Component {

  state = {
    showChildrenLine: false,
  };

  componentWillReceiveProps(props) {
    if (props.params.objectiveId != this.props.params.objectiveId) {
      this.props.actions.resetOkr();
      this.fetchContent(props);
    }

    if (util.isNull(this.props.okr.children) && !util.isNull(props.okr.children)) {
      setTimeout(() => {
        if (this.unmount) return;
        this.setState({
          showChildrenLine: true,
        });
      }, 300);
    }
  }

  componentDidMount() {
    this.props.actions.resetOkr();
    this.fetchContent();
    this.el = findDOMNode(this);
  }

  componentWillUnmount() {
    this.unmount = true;
    this.props.actions.resetOkr();
  }

  fetchContent(props) {
    props = props || this.props;
    const { objectiveId } = props.params;

    this.props.actions.fetchObjectiveDetail(objectiveId);
    this.props.actions.fetchObjectiveAncester(objectiveId);
    this.props.actions.fetchObjectiveChildren(objectiveId);
  }

  getCardTo(obj) {
    if (obj === null) return null;
    const { query } = this.props.location;
    if (obj.hasSubordinate /*&& obj.hasParent*/) {
      return `#/objectives/${obj.objectiveId}/relative-tree?${util.body(query)}`;
    }
    return null;
  }

  renderSelf() {
    const { detail, ancester, children } = this.props.okr;
    let list = sliceArray(children || [], 4);

    if (children && children.length < 4) list = [list];

    let verticalLine = list.length > 1
      ? ((list.length - 1) * 180 + 40 + 24)
      : 24;

    if (ancester == null) return null;

    return (
      <div style={{ position: 'relative' }}>
        {
          !util.isNull(ancester) ?
          <Motion defaultStyle={{ height: 0 }} style={{ height: spring(40, { damping: 30,stiffness: 280, }) }}>
            {
              ({ height }) => (
                <div style={{
                  height: `${height}px`,
                  top: `${40 - height}px`,
                  position: 'absolute',
                  width: '1px',
                  backgroundColor: '#BCC5CE',
                  left: '50%',
                  marginLeft: '-1px',
                }}></div>
              )
            }
          </Motion> : null
        }
        <Card
          className={style.self}
          isSelf={true}
          query={this.props.location.query}
          to={this.getCardTo(detail)}
          {...detail}
        />
        {
          !util.isNull(children) ? 
          <Motion
            defaultStyle={{ height: 0 }}
            style={{ height: spring(verticalLine, { damping: 30,stiffness: 280, }) }}
          >
            {
              ({ height }) => (
                <div style={{
                  height: `${height}px`,
                  bottom: `${40 - height}px`,
                  position: 'absolute',
                  width: '1px',
                  backgroundColor: '#BCC5CE',
                  left: '50%',
                  marginLeft: '-1px',
                }}></div>
              )
            }
          </Motion> : null
        }
      </div>
    );
  }

  renderParent() {
    const { ancester, detail } = this.props.okr;
    if (ancester === null) return <div style={{ width: '268px', height: '132px' }}></div>;
    if (detail === null) return <div style={{ width: '268px', height: '132px' }}></div>;

    if (util.isNull(ancester)) return null;
    const hasParent = ancester[0].hasParent;
    return (
      <div className={cx({
        [style['parent-card-wrapper']]: true,
        [style['isparent']]: !hasParent
      })}>
        <Card
          className={style.parent}
          isParent
          query={this.props.location.query}
          to={this.getCardTo(ancester[0])}
          {...ancester[0]}
        />
      </div>
    );
  }

  renderChildren() {
    const { children, detail, ancester, } = this.props.okr;
    if (util.isNull(children)) return null;
    if (detail === null || ancester === null) return null;

    let list = sliceArray(children, 4);
    if (children.length < 4) list = [list];

    return (
      <div>
        {
          list.map((group, i) => (
            <div
              className={style.children}
              key={i}
            >
              <Motion
                defaultStyle={{ width: 0 }}
                style={{
                  width: spring(group.length * 268 - 268 + 20 * (group.length-1), {
                    damping: 30, stiffness: 280,
                  }),
                }}
              >
                {
                  ({ width }) => (
                    <b
                      style={{
                        height: '1px',
                        position: 'absolute',
                        top: '-16px',
                        backgroundColor: '#BCC5CE',
                        width: `${width}px`,
                        left: '50%',
                        marginLeft: `-${width/2}px`,
                        fontWeight: 'normal',
                      }}
                    />
                  )
                }
              </Motion>
              {
                group.map((child, i) => (
                  <div key={i}>
                    <Card
                      query={this.props.location.query}
                      to={this.getCardTo(child)}
                      {...child}
                    />
                    {
                      this.state.showChildrenLine ? (
                        <Motion defaultStyle={{ height: 0 }} style={{ height: spring(16, { damping: 30,stiffness: 280, }) }}>
                          {
                            ({ height }) => (
                              <div style={{
                                marginBottom: `${16 - height}px`,
                                height: `${height}px`,
                                bottom: '100%',
                                position: 'absolute',
                                width: '1px',
                                backgroundColor: '#BCC5CE',
                                left: '50%',
                                marginLeft: '-1px',
                              }}></div>
                            )
                          }
                        </Motion>
                      ) : null
                    }
                  </div>
                ))
              }
            </div>
          ))
        }
      </div>
    );
  }

  renderCards() {
    return (
      <div>
        {
          this.renderParent()
        }
        {
          this.renderSelf()
        }
        {
          this.renderChildren()
        }
      </div>
    );
  }

  render() {
    const { pathname, query, } = this.props.location;
    const { objectiveId } = this.props.params;  
    return (
      <div
        className={style.root}
      >
        <ul className={style.nav}>
          <li>
            <Link
              activeClassName={style.active}
              to={`/objectives/${objectiveId}/relative-tree?${util.body(query)}`} label="卡片视图"
            />
          </li>
          <li>
            <Link
              onClick={() => {
                if (this.props.app.naviStep === 7 && this.props.app.guide == 4) {
                  this.props.actions.updateGuide(8);
                }
              }}
              to={`/objectives/${objectiveId}/bird-view?${util.body(query)}`}
              label="鸟瞰图"
            />
          </li>
          {
            (this.props.app.naviStep === 7 && this.props.app.guide == 4) ? (
              <NextGuide
                left
                large
                styles={{
                  left: '-98px',
                  bottom: '-10px'
                }}
                str="点击这里，查看更宏观的鸟瞰图"
              />
            ) : null
          }
        </ul>
        <ul className={style.tip}>
          <li>
            <i style={{ backgroundColor: '#7AD1AF' }}></i>
            <span>个人目标</span>
          </li>
          <li>
            <i style={{ backgroundColor: '#FFA45B' }}></i>
            <span>团队目标</span>
          </li>
        </ul>
        { this.renderCards() }
      </div>
    );
  }
}
